//
//  EmoticionPackage.swift
//  KeyboardDemo
//
//  Created by Lucky on 16/5/13.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit

class EmoticonPackage: NSObject {
    
    // 单例
    private static let packageList: [EmoticonPackage] = EmoticonPackage.loadPackages()
    
    class func shareEmoticonPackages() -> [EmoticonPackage] {
        return packageList
    }
    
    /// 当前组表情文件夹的名称
    var id: String?
    /// 组的名称
    var group_name_cn: String?
    /// 当前组的表情对象
    var emoticons: [Emoticon]?
    
    /// 获取所有表情分组数据
    private class func loadPackages() -> [EmoticonPackage] {
        
        var packages = [EmoticonPackage]()
        
        // 创建最近表情组
        let currentPackages = EmoticonPackage(id: "")
        currentPackages.group_name_cn = "最近"
        currentPackages.emoticons = [Emoticon]()
        currentPackages.appendEmptyEmoticons()
        packages.append(currentPackages)
        
        // 加载emoticons.plist
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        
        let dict = NSDictionary(contentsOfFile: path)!
        // 从emoticons中获取packages
        let dictArray = dict["packages"] as! [[String: AnyObject]]
        print(dictArray)
        // 遍历packages数据
        
        for d in dictArray {
            let package = EmoticonPackage(id: d["id"] as! String)
            packages.append(package)
            package.loadEmoicons()
            package.appendEmptyEmoticons()
        }
        
        //取出id
        
        return packages
    }
    
    /**
     加载每一组中所有的表情
     */
    func loadEmoicons() {
        let emoticonDict = NSDictionary(contentsOfFile: infoPath())
        
        group_name_cn = emoticonDict!["group_name_cn"] as? String
        
        let dictArray = emoticonDict!["emoticons"] as! [[String: String]]
        
        emoticons = [Emoticon]()
        
        var index = 0
        
        for dict in dictArray {
            
            if  index == 20 {
                emoticons?.append(Emoticon(isRemoveButton: true))
                index = 0
            }
            emoticons?.append(Emoticon(dict: dict, id: id!))
            
            index++
        }
        
    }
    
    /**
     添加空白按钮，如果一页不足21个，就用空白按钮补齐
     */
    func appendEmptyEmoticons() -> () {
        let count = emoticons!.count % 21
        
        for _ in count..<20 {
            //添加空白补位按钮
            emoticons?.append(Emoticon(isRemoveButton: false))
        }
        //添加最后一个删除按钮
        emoticons?.append(Emoticon(isRemoveButton: true))
        
    }
    
    /// 给最近表情添加数据
    func appendCurrentEmoticon(emoticon: Emoticon) {
        
        //删除按钮不添加
        if emoticon.isRemoveButton {
            return
        }
        
        //是否已经添加过
        let contains = emoticons!.contains(emoticon)

        //没添加过添加
        if !contains {
            emoticons?.removeLast()
            emoticons?.append(emoticon)
        }
        
        //按使用次数排序
        var result = emoticons?.sort({ (e1 , e2) -> Bool in
            return e1.times > e2.times
        })
        
        //删除多余的
        if !contains {
            result?.removeLast()
            result?.append(Emoticon(isRemoveButton: true))
        }
        
        emoticons = result
    }
    
    /**
     获取该组中info.plist文件的路径
     */
    func infoPath() -> String {
        return (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent("info.plist")
    }
    
    /**
     获取bundle文件的跟路径
     */
    class func emoticonPath() -> NSString {
        return (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle")
    }
    
    init(id: String) {
        self.id = id
    }
    
}

class Emoticon: NSObject {
    /// 表情对应的文字
    var chs: String?
    /// 表情对应的图片
    var png: String? {
        didSet {
            imagePath = (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
        }
    }
    
    
    /// 表情对应的十六进制字符串
    var code: String? {
        didSet {
            
            let scanner = NSScanner(string: code!)
            
            var result:UInt32 = 0
            scanner.scanHexInt(&result)
            
            emojiStr = "\(Character(UnicodeScalar(result)))"
            
        }
    }
    /// 当前表情对应的文件夹
    var id: String?
    /// 表情图片的全路径
    var imagePath: String?
    /// emoji字符串
    var emojiStr: String?
    /// 标记是是否是删除按钮
    var isRemoveButton: Bool = false
    /// 记录当前表情被使用的次数
    var times: Int = 0
    
    init(isRemoveButton: Bool) {
        super.init()
        self.isRemoveButton = isRemoveButton
    }
    
    init(dict: [String: String], id: String) {
        super.init()
        self.id = id
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}
